package service

import (
	"day12_12_homework/config"
	"day12_12_homework/internal/models/dao"
	"gorm.io/gorm"
	"strconv"
)

func CreateIntroduction(userId int, name, cover, intros string) (int, string) {
	intro := dao.Introduction{
		UserId: userId,
		Name:   name,
		Cover:  cover,
		Intro:  intros,
	}
	err := config.DB.Debug().Model(&dao.Introduction{}).Create(&intro).Error
	if err != nil {
		return 0, "攻略发布失败"
	}
	return int(intro.ID), ""
}

func ListIntroduction(keyWord string, page, pageSize int) ([]*dao.Introduction, string) {
	query := config.DB.Model(&dao.Introduction{})
	var listIntro []*dao.Introduction
	if keyWord != "" {
		err := query.Where("name like ?", keyWord).Scopes(Paginate(page, pageSize)).Find(&listIntro).Error
		if err != nil {
			return nil, "查询失败"
		}
		return listIntro, ""
	}
	err := query.Scopes(Paginate(page, pageSize)).Find(&listIntro).Error
	if err != nil {
		return nil, "查询失败"
	}
	return listIntro, ""
}

func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		page, _ = strconv.Atoi(strconv.Itoa(page))
		if page <= 0 {
			page = 1
		}

		pageSize, _ = strconv.Atoi(strconv.Itoa(pageSize))
		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}
